<?php 
	class Utility
	{
		private static $arr_js = array();
		static function addScript($path,$key = "",$arr_func = array())
		{
			if(self::canAddJS($key))
			{
				self::addJS($path,$key,$arr_func);
				self::$arr_js[$key] = $path;
			}
		}
		
		static function addJS($path,$key,$arr_func = array())
		{
			$funcs = "";
			foreach ($arr_func as $data)
			{
				if(!empty($data))
					$funcs .= $data;
			}
			
			$js = array();
			$js[$key] = "$path";
			echo "<script>
					head.js('index.php',function(){
						
					});
				 </script>";
		}
		
		static function includeJS($path,$key = "",$arr_func = array())
		{
			if($key == "") $key = "Modernizr_emptyelement";
			$key_lower = strtolower($key);
			$funcs = "";
			foreach ($arr_func as $data)
			{
				if(!empty($data))
					$funcs .= $data;
			}
			
			$js = "<script>
						Modernizr.addTest('$key_lower',(typeof($key) == 'undefined'));
						Modernizr.load({
							test: Modernizr.$key_lower,
							yep: '$path',
							complete:function(){
								
								$funcs
							}
						});
					</script>
				";
			echo $js;
		}
		
		static function save($table,$post)
		{
			if (!$table->bind( $post )) {
				return JError::raiseWarning( 500, $table->getError() );
				exit();
			}
			if (!$table->store()) {
				JError::raiseError(500, $table->getError() );
				exit();
			}
			return $table;
		}
		
		static function canAddJS($key)
		{
			return !isset(self::$arr_js[$key]);
		}
		
		static function uploadImages($uploadname)
		{	
			
			$arr_dbname = array();	
			$result = array("success"=>true,"error"=>"","data"=>$arr_dbname);
			if (!empty($_FILES[$uploadname]))
			{
				$root = JPATH_SITE . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'fileupload';
				$arr_extensions = array("png","gif","jpg","jpeg");
				foreach ($_FILES[$uploadname]["name"] as $i=>$fileupload)
				{
					$name = $_FILES[$uploadname]["name"][$i];
					$tmp = $_FILES[$uploadname]["tmp_name"][$i];
					$size = $_FILES[$uploadname]["size"][$i];
					
					$extension = strtolower(self::getExtension(stripslashes($name)));
					$imgname = base64_encode(self::getImgName(stripslashes($name)));
					$dbname = $imgname.'.'.$extension;
					$destination = $root.DIRECTORY_SEPARATOR.$imgname.'.'.$extension;
					
					$count_img = 0;
					while (file_exists($destination)) {
						$count_img++;
						$tmp_name = $imgname;
		                $tmp_name = base64_decode($tmp_name) . '_' . $count_img;
		                $tmp_name = base64_encode($tmp_name);
		                $dbname = $tmp_name.'.'.$extension;
		                $destination = $root.DIRECTORY_SEPARATOR.$tmp_name.'.'.$extension;	  		                           
		            }
		            
					if(in_array($extension,$arr_extensions))
					{
						if(!move_uploaded_file($tmp, $destination)) {
							$result["success"] = false;
							$result["error"] = "Upload hình thất bại";
							break;
						}else 
						{
							$arr_dbname[] = $dbname;
							$result["data"] = $arr_dbname;
						}
					}
				}
			}
			return $result;
		}
		
		static function getExtension($str) {
	
			$i = strrpos($str,".");
			if (!$i) { return ""; } 
	
			$l = strlen($str) - $i;
			$ext = substr($str,$i+1,$l);
			return $ext;
		}
		
		static function getImgName($str) {
	
	        $i = strrpos($str,".");
	        if (!$i) { return ""; } 
	
	        $l = strlen($str) - $i;
	        $ext = substr($str,0,$i);
	        return $ext;
		}
		
		public static function getActions($section)
		{
			$user	= JFactory::getUser();
			$result	= new JObject;
	
			$assetName = "com_ketnoi.$section";
			$level = $section;
	
			$actions = JAccess::getActions('com_ketnoi', $level);
			
			foreach ($actions as $action)
			{
				$result->set($action->name,	$user->authorise($action->name, $assetName));
			}
	
			return $result;
		}
		
		static function showError()
		{
			return "<div class='alert alert-error invalid_permission'>
					<strong>Bạn không có quyền truy cập</strong>
				</div>";
		}
		
		static function checkAccess($action,$canDo)
		{
			return $canDo->get($action);
		}
		
		static function isAdmin()
		{
			$user = JFactory::getUser();
			return $user->get("isRoot");
		}
		
		static function buildCacheLinhkien()
		{
			$cache_dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
			$cache_filename = $cache_dir."linhkien.php";
			$db = JFactory::getDbo();
			$query = "select * from #__products where product_type = 'linhkien' and is_delete = 0";
			$db->setQuery($query);
			$result = $db->loadAssocList();
			if(JFile::exists($cache_filename))
			{
				JFile::delete($cache_filename);
			}
			ob_start();
			var_export($result);
			$out = ob_get_clean();
			$str = '<?php  $cache_linhkien =  ';
			file_put_contents($cache_filename,$str . $out . '; ?>');
		}
		
		static function buildCacheMayPhoto()
		{
			$cache_dir = dirname(__FILE__).DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
			$cache_filename = $cache_dir."mayphoto.php";
			$db = JFactory::getDbo();
			$query = "select * from #__products where product_type = 'mayphoto' and is_delete = 0";
			$db->setQuery($query);
			$result = $db->loadAssocList();
			if(JFile::exists($cache_filename))
			{
				JFile::delete($cache_filename);
			}
			ob_start();
			var_export($result);
			$out = ob_get_clean();
			$str = '<?php  $cache_mayphoto =  ';
			file_put_contents($cache_filename,$str . $out . '; ?>');
		}
	}

?>